package com.baiyinet.util;

import android.content.Context;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;

import myandroid.library.loader.HttpConnection;

/**
 * @author J.Huang
 * @version 1.0
 * @since 17/1/9
 */

public class CookieHelper {
    public CookieHelper() {
    }

    public static void setWebViewRequestUrlCookie(Context context, String requestUrl, String cookieInfo) {
        if(!"".equals(cookieInfo)) {
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.setCookie(requestUrl, cookieInfo);
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                cookieManager.flush();
            } else {
                // 在android4.X系统下面CookieSyncManager的方法有些是异步的，removeSeesionCookie()和sync()要等待100毫秒。
                // 而在android5.0以上的系统Cookie是同步的,sync=flush方法，调用CookieManager.flush()就是同步设置cookie。
                CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(context);
                cookieSyncManager.sync();
            }
        }
    }

    public static String getWebViewRequestUrlCookie(Context context, String requestUrl) {
        String result = "";
        CookieManager cookieManager = CookieManager.getInstance();
        if(cookieManager.getCookie(requestUrl) != null) {
            result = cookieManager.getCookie(requestUrl);
        }

        return result;
    }

    public static void RemoveCookie(Context context) {
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
    }

    public static void setHttpCookie(String cookie) {
        HttpConnection.setCookie(cookie);
    }

    public static String getHttpCookie() {
        return HttpConnection.getCookie();
    }
}
